# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2022/7/26 0026 1:19
# @Author    :jiaxuesong


'''
查找目标用例生成测试套件，执行测试套件生成测试报告；自动清理报告；发送邮件
导包：
    查找目标用例，生成测试套件
        unittest.TestLoader().discover()
'''

import time
import os, unittest
from appium_test.common.log import logger
from appium_test.common.sendEmail import SendEmail
import HTMLTestRunner
from appium_test.common.driver import Driver
from multiprocessing import Pool

#查找目标文件生成测试套件
def loader():
    # 查找用例保存目录
    case_file = os.path.dirname(__file__) + r'/testCase/'
    # 生成测试套件
    load = unittest.TestLoader().discover(start_dir=case_file, pattern='test*.py')
    return load


#自动清理报告
def clear_file():
    # 查找测试报告保存路径
    re_path = os.path.dirname(__file__) + r'/testReport/'
    # 获取文件列表
    file_list = os.listdir(re_path)
    #循环便利文件，并删除旧文件
    # 获取测试报告生成时间，并排序
    file_list.sort(key=lambda x: os.path.getctime(re_path + x))
    for i in file_list[:-3]:
        if '.html' in i:
            os.remove(re_path + i)

#执行测试套件生成测试报告
def run_suit(x, y):
    Driver.device_name = x
    Driver.port = y

    clear_file()
    suit = loader()
    #创建测试报告保存路径及命名
    t = time.strftime('%Y_%m_%d_%H_%M_%S', time.localtime())
    report = os.path.dirname(__file__) + r'/testReport/' + t + '_report.html'
    # 以写入方式打开文件
    with open(report, 'wb') as r:
        runner = HTMLTestRunner.HTMLTestReportCN(stream=r, verbosity=2, title='自动化测试报告', description='自动化测试结果')
        runner.run(suit)
    #实例化发送邮件函数
    se = SendEmail()
    while True:
        if os.path.exists(report):
            se.send_email(report)
            break

if __name__ == '__main__':
    serverlist = [('127.0.0.1:21503', '4723'), ('127.0.0.1:21513', '4725')]
    # 实例化Pool方法
    pool = Pool(len(serverlist))
    re = []
    for i, j in serverlist:
        res = pool.apply_async(run_suit, (i, j))
        re.append(res)

    for i in re:
        i.get()

    print('运行成功！')
